from threading import Timer
from selenium.webdriver.remote.webdriver import WebElement


class ElementHighlighted:
    # 实例
    __instance = None
    # 是否执行过初始化方法
    __init_flag = False

    elements = []
    source_styles = []
    timer = None

    highlighted_style = 'color: #f00; box-shadow: 0px 0px 10px #f00;'

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self, perform, element: WebElement or list):
        self.clear_highlighted()
        self.source_styles = []
        self.perform = perform
        self.elements = element if type(element) == list else [element]
        if self.__class__.__init_flag:
            return
        self.__class__.__init_flag = True

    def get_style(self) -> list:
        script = "return arguments[0].getAttribute('style',arguments[1]);"
        try:
            return [self.perform.driver.execute_script(script, element) for element in self.elements]
        except Exception as e:
            return []

    def set_style(self, styles: list):
        for index in range(len(self.elements)):
            try:
                self.perform.driver.execute_script(
                    "arguments[0].setAttribute('style',arguments[1]);",
                    self.elements[index],
                    styles[index])
            except Exception as e:
                pass

    def set_highlighted(self):
        self.source_styles = self.get_style()
        h_styles = ['%s%s' % (style, self.highlighted_style) for style in self.source_styles]
        self.set_style(h_styles)
        if self.timer is not None:
            self.timer.cancel()
            self.timer = None
        self.timer = Timer(3, self.clear_highlighted, ())
        self.timer.start()

    def clear_highlighted(self):
        if len(self.source_styles) > 0:
            self.set_style(self.source_styles)
        self.source_styles = []
        self.elements = []
        self.perform = None

    @classmethod
    def highlighted(cls, perform, element: WebElement or list):
        obj = cls(perform, element)
        obj.set_highlighted()